package com.kara.woodAgent.agent.wood.node;

import com.kara.woodAgent.agent.graph.Next;
import com.kara.woodAgent.agent.graph.Node;
import com.kara.woodAgent.agent.model.ModelProvider;
import com.kara.woodAgent.agent.tool.provider.ToolProvider;
import com.kara.woodAgent.agent.wood.context.WoodReactContext;
import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.chat.request.ChatRequest;
import dev.langchain4j.model.chat.response.ChatResponse;

import java.util.List;

/**
 * @author tzy
 * @version 1.0
 * @project wood_agent
 * @description
 * @date 2025/6/11 12:21:51
 */
public class ThinkNode implements Node<WoodReactContext> {

	private final ModelProvider modelProvider;

	private final ToolProvider.ToolServiceHolder toolProviderHolder;


	public ThinkNode(ModelProvider modelProvider, ToolProvider.ToolServiceHolder toolProviderHolder) {
		this.modelProvider = modelProvider;
		this.toolProviderHolder = toolProviderHolder;
	}

	@Override
	public Next execute(WoodReactContext context) {

		List<ChatMessage> chatMessages = context.getChatMessages();
		ChatLanguageModel chatModel = modelProvider.getChatModel();

		UserMessage userMessage = UserMessage.from("""
                            #### 注意
                			请你根据当前的执行情况你,分析下一步要做什么,你应该考虑以下问题:
                                1. 您需要创建或完善计划吗？
                                2. 您准备好执行特定步骤了吗？
                                3. 你完成了任务吗？
                            提供推理，然后选择适当的工具工作。
                            *** 强制要求 *** 当你完成所有任务之后，你必须调用exit工具，并且告知我你已经完成了所有任务。
                """);
		chatMessages.add(userMessage);
		ChatRequest request = ChatRequest.builder()
				.toolSpecifications(toolProviderHolder.toolSpecifications())
				.messages(chatMessages).build();
		ChatResponse chatResponse = chatModel.chat(request);

		AiMessage aiMessage = chatResponse.aiMessage();
		chatMessages.add(aiMessage);

		if (aiMessage.hasToolExecutionRequests()) {
			context.setToolExecutionRequest(aiMessage.toolExecutionRequests());
			return Next.NextNode("tool").step(aiMessage.toString());
		} else {
			return Next.NextNode("model").step(aiMessage.toString());
		}
	}
}
